package lily.phs.object;

/**
 * 身份证号码类
 * @author heckaitor
 *
 */
public class IDCard{

	private String id;
	private int numbers;//位数:15 or 18
	private String province_code;
	private String city_code;
	private String area_code;
	private String birth_year;
	private String birth_month;
	private String birth_day;
	private String serial_code;
	private String verify_code;
	
	
	public IDCard(String id){
		this.id = id;
		numbers = id.length();
		System.out.println("身份证号码位数="+numbers);
		province_code = id.substring(0, 2);
		city_code = id.substring(2, 4);
		area_code = id.substring(4, 6);
		if(numbers==15){
			birth_year = id.substring(6, 8);
			birth_month = id.substring(8,10);
			birth_day = id.substring(10, 12);
			serial_code = id.substring(12, 15);
		}
		else if(numbers==18){
			birth_year = id.substring(6, 10);
			birth_month = id.substring(10,12);
			birth_day = id.substring(12, 14);
			serial_code = id.substring(14, 17);
			verify_code = id.substring(17, 18);
		}
		
		
		
	}
	
	/**
	 * @return 地区编码（前6位）
	 */
	public String getArea(){
		String area = province_code + city_code + area_code;
		return area;
	}
	
	/**
	 * @return 出生日期
	 */
	public String getBirthday(){
		String birth = "";
		if(numbers==15){
			birth = "19" + birth_year +"-"+ birth_month +"-"+ birth_day;
		}
		else if(numbers==18){
			birth = birth_year +"-"+ birth_month +"-"+ birth_day;
		}
		return birth;
	}
	
	/**
	 * @return 性别：1男，0女
	 */
	public int getGender(){
		int gender = -1;
		gender = Integer.parseInt(serial_code.substring(2));
		gender%=2;
		return gender;
	}
	
	/**
	 * 计算校验码,身份证号为18位
	 */
	private String calVerifyCode(){
		int[] W = new int[]{7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2};
		int sum = 0;
		for(int i=0;i<17;i++){
			int A = Integer.parseInt(id.substring(i, i+1));
			sum += A*W[i];
		}
		int code = sum%11;
		switch(code){
		case 0:
			return "1";
		case 1:
			return "0";
		case 2:
			return "x";
		case 3:
			return "9";
		case 4:
			return "8";
		case 5:
			return "7";
		case 6:
			return "6";
		case 7:
			return "5";
		case 8:
			return "4";
		case 9:
			return "3";
		case 10:
			return "2";
		default:
			return "";
		}
		
	}
	
	/**
	 * 检验身份证号是否有效
	 * @return 有效：true
	 */
	public boolean isValid(){
		if(numbers==15){
			return true;
		}
		else if((numbers==18)&&(calVerifyCode().equals(verify_code))){
			return true;
		}
		else{
			return false;
		}
	}
}
